package cartoonsface

import logic.LogicFace
import logic.Score
import logic.ScoreElement


class CartoonController {

	String tempImagesPath = "web-app/images/imagesCartoons/temp/";
	String cartoonsImagesPath = "/web-app/images/imagesCartoons/cartoons/"
	public static LogicFace logicFace

	def index = {
		redirect(action: "create", params: params)
	}

	def create = {
	}

	def generate = {
		String imageName = params.foto.getOriginalFilename()
		
		if (!imageName.endsWith(".jpg") && !imageName.endsWith(".JPG") && !imageName.endsWith(".png") && !imageName.endsWith(".PNG")){
			flash.message = "Apenas imagens JPG ou PNG!"
			redirect(action: "create")
		}
		
		String path = tempImagesPath + imageName;
		File image = new File (path);
		image.createNewFile()
		FileOutputStream fos = new FileOutputStream(path);
		fos.write(params.foto.bytes);
		fos.close()



		logicFace = LogicFace.getInstance("f1454d2b088878a684ee6ed43ceb3055",
				"d2f88bed9cd6485ae94ad5791885d62c");

		logicFace.setPathCSV("web-app/files/DBImages.csv");
		logicFace.setPathImages("web-app/images/imagesCartoons");

		Score score = logicFace.searchFace(image)
		//image.delete()
		
		render(view: "show", model: [images: getImages (score.list(), 4), inImage:imageName, descriptions:getDescriptions (score.list(), logicFace, 4), names:getCleanNames (score.list(), logicFace, 4), listElements:score.list().subList(0,4)])
	}

	def show = {
	}

	def getImages (List<ScoreElement> scores, int max){

		TreeMap<String, String> images = new TreeMap<String, String>();
		
		for (int i=0; i<max; i++){
			images.put(scores.get(i).name + ".jpg", scores.get(i).value.toString().substring(0, 5) + "%");
		}
		
		return images;
	}
	
	def getDescriptions (List<ScoreElement> scores, LogicFace logicFace, int max){
		TreeMap<String, String> descriptions = new TreeMap<String, String>();
		
				for (int i=0; i<max; i++){
					descriptions.putAll(logicFace.extractNameAndDescription(scores.get(i).name))
				}
				
	return descriptions;
		
	}
	
	def getCleanNames (List<ScoreElement> scores, LogicFace logicFace, int max){
		TreeMap<String, String> descriptions = new TreeMap<String, String>();
		
				for (int i=0; i<max; i++){
					int pos = scores.get(i).name.indexOf("_")
					descriptions.put(scores.get(i).name, scores.get(i).name.substring(0, pos).replaceAll("-", " "))
				}
				
	return descriptions;
		
	}
	
	def showtrainer = {
		String path = tempImagesPath + params.imageName;
		File image = new File (path);
		
		Score score = logicFace.searchFace(image)
		int max = 11
		render(view: "showtrainer", model: [images: getImages (score.list(), max), inImage:params.imageName, descriptions:getDescriptions (score.list(), logicFace, max), names:getCleanNames (score.list(), logicFace, max), listElements:score.list().subList(0,max)])
	}
	
	def trainer = {
		String cartoon = params.cartoon
		File userImage = new File(tempImagesPath + params.user)
		logicFace.adjust(userImage, cartoon);
		redirect(action: "index")
	}

}
